from django.contrib.auth.hashers import check_password
from rest_framework.decorators import api_view
from rest_framework.views import APIView
from .serializers import (UserDataSerializer, ProductSerializer,OperationSerializer, NormalOrderSerializer)
import hashlib
import time
from qkd_app.models import qkd_keys

# 简单的数据获取视图
def get_data(request):
    data = {
        "message": "Hello from Django!",
        "status": "success",
        "users": ["Alice", "Bob", "Charlie"],
    }
    return JsonResponse(data)


# Ping视图，用于检测服务器状态
@api_view(['GET'])
def ping(request):
    """简单的ping接口，用于检测服务器状态"""
    return Response({"status": "success", "message": "pong"})

class RegisterView(APIView):
    def post(self, request):
        data = request.data.copy()
        username = data.get('username')
        is_encrypted = data.get('is_encrypted', False)

        # 检查是否是加密数据
        if is_encrypted:
            # 打印调试信息
            print(f"接收到加密注册请求，用户名: {username}")
            print(f"qkd_keys字典内容: {list(qkd_keys.keys())}")

            # 检查用户名是否在qkd_keys中
            if username not in qkd_keys:
                return Response({
                    'status': 'error',
                    'message': f'未找到用户 {username} 的QKD密钥，请先重新生成量子密钥'
                }, status=status.HTTP_400_BAD_REQUEST)

            try:
                # 获取正确的密钥
                qkd_key = qkd_keys[username]
                print(f"找到QKD密钥: {qkd_key[:6]}...")  # 仅打印前6位字符保护隐私

                # 解密密码
                encrypted_password = data.get('password', '')
                decrypted_password = AESCipher.decrypt(encrypted_password, username)
                #encrypted_password = data.get('password', '')
                #decrypted_password = AESCipher.decrypt(encrypted_password, qkd_key)

                if decrypted_password is None:
                    return Response({
                        'status': 'error',
                        'message': '密码解密失败'
                    }, status=status.HTTP_400_BAD_REQUEST)

                # 更新请求数据，使用解密后的密码
                data['password'] = decrypted_password

                # 如果电子邮箱和手机号也加密了，解密它们
                if 'email' in data and data['email']:
                    decrypted_email = AESCipher.decrypt(data['email'], username)
                    if decrypted_email:
                        data['email'] = decrypted_email

                if 'phone' in data and data['phone']:
                    decrypted_phone = AESCipher.decrypt(data['phone'], username)
                    if decrypted_phone:
                        data['phone'] = decrypted_phone
            except Exception as e:
                print(f"解密过程出错: {str(e)}")
                return Response({
                    'status': 'error',
                    'message': f'解密失败: {str(e)}'
                }, status=status.HTTP_400_BAD_REQUEST)

        # 获取店铺名和邀请码
        store_name = data.get('shop_name')
        invite_code = data.get('invite_code', '')

        # 检查是否存在该店铺
        existing_shop = Shop.objects.filter(name=store_name).first()
        is_first_store = not existing_shop

        # 如果不是首次注册该店铺且未提供邀请码或邀请码不正确
        if not is_first_store:
            if not invite_code:
                return Response({
                    'status': 'error',
                    'message': '该店铺已存在，需要邀请码'
                }, status=status.HTTP_400_BAD_REQUEST)

            if not check_password(invite_code, existing_shop.invite_code):
                return Response({
                    'status': 'error',
                    'message': '邀请码无效，请联系店铺管理员获取正确邀请码!!!'
                }, status=status.HTTP_400_BAD_REQUEST)

        # 创建用户
        serializer = UserDataSerializer(data=data)
        if serializer.is_valid():
            user = serializer.save()

            # 如果是首次注册该店铺，生成并保存邀请码
            if is_first_store:
                shop = user.shop
                # 生成新的邀请码
                new_invite_code = generate_invite_code(store_name)
                shop.invite_code = new_invite_code
                shop.save()

                return Response({
                    'status': 'success',
                    'message': '注册成功',
                    'data': serializer.data,
                    'is_first_store': True,
                    'shop_invite_code': new_invite_code
                }, status=status.HTTP_201_CREATED)
            else:
                return Response({
                    'status': 'success',
                    'message': '注册成功',
                    'data': serializer.data,
                    'is_first_store': False
                }, status=status.HTTP_201_CREATED)
        return Response({
            'status': 'error',
            'errors': serializer.errors
        }, status=status.HTTP_400_BAD_REQUEST)

# 邀请码生成函数
def generate_invite_code(store_name):
    base = f"{store_name}_{time.time()}"
    invite_code = hashlib.md5(base.encode()).hexdigest()[:8].upper()
    return invite_code

# 修改后的登录视图
class LoginView(APIView):
    def post(self, request):
        data = request.data.copy()
        username = data.get("username")
        password = data.get("password")
        is_encrypted = data.get('is_encrypted', False)

        if not username:
            return Response({
                "status": "error",
                "errors": ["用户名不能为空"]
            }, status=status.HTTP_400_BAD_REQUEST)

        # 处理加密登录
        if is_encrypted:
            # 检查用户是否有QKD密钥
            if username not in qkd_keys:
                return Response({
                    "status": "error",
                    "errors": ["未找到QKD密钥，请重新生成量子密钥"]
                }, status=status.HTTP_400_BAD_REQUEST)

            # 解密密码
            decrypted_password = AESCipher.decrypt(password, username)
            if decrypted_password is None:
                return Response({
                    "status": "error",
                    "errors": ["密码解密失败"]
                }, status=status.HTTP_400_BAD_REQUEST)

            # 使用解密后的密码
            password = decrypted_password

        try:
            user = UserData.objects.get(username=username)
            if check_password(password, user.password):
                # 生成令牌
                import uuid
                token_key = str(uuid.uuid4())

                return Response({
                    "status": "success",
                    "message": "登录成功",
                    "user": {
                        "username": user.username,
                        "shop_name": user.shop.name
                    },
                    "token": token_key,
                    "use_qkd": username in qkd_keys  # 告知客户端是否使用QKD加密
                }, status=status.HTTP_200_OK)
            else:
                return Response({
                    "status": "error",
                    "errors": ["账号或密码错误"]
                }, status=status.HTTP_401_UNAUTHORIZED)
        except UserData.DoesNotExist:
            return Response({
                "status": "error",
                "errors": ["账号或密码错误"]
            }, status=status.HTTP_401_UNAUTHORIZED)
        except Exception as e:
            print(f"登录错误: {str(e)}")
            return Response({
                "status": "error",
                "errors": [f"登录过程中发生错误: {str(e)}"]
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


# 验证用户是否有QKD密钥视图
@api_view(['POST'])
def check_qkd_available(request):
    #检查用户是否有可用的QKD密钥
    username = request.data.get("username")

    if not username:
        return Response({
            "status": "error",
            "message": "用户名不能为空"
        }, status=status.HTTP_400_BAD_REQUEST)

    has_key = username in qkd_keys

    return Response({
        "status": "success",
        "has_key": has_key,
        "message": "用户有QKD密钥" if has_key else "用户没有QKD密钥"
    })

# 用户信息视

@api_view(['GET'])
def user_info(request):
    #获取用户详细信息，包括所属店铺
    username = request.GET.get('username')

    if not username:
        return Response({"error": "必须提供用户名"}, status=status.HTTP_400_BAD_REQUEST)

    try:
        user = UserData.objects.get(username=username)
        return Response({
            "user_id": user.id,
            "username": user.username,
            "email": user.email,
            "phone": user.phone,
            "province": user.province,  # 从用户模型获取省份
            "shop_id": user.shop.id,
            "shop_name": user.shop.name,
            "shop_type": user.shop.shop_type,
            "is_cross_border": user.shop.is_cross_border
        })
    except UserData.DoesNotExist:
        return Response({"error": "用户不存在"}, status=status.HTTP_404_NOT_FOUND)

# 产品列表视图
@api_view(['GET', 'POST'])
def product_list(request):
    # 从请求中获取用户信息
    username = request.GET.get('username') or request.data.get('username')

    if not username:
        return Response({"error": "必须提供用户名"}, status=status.HTTP_400_BAD_REQUEST)

    try:
        # 查找用户并获取关联的店铺
        user = UserData.objects.get(username=username)
        shop = user.shop
    except UserData.DoesNotExist:
        return Response({"error": "用户不存在"}, status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        # 获取该店铺的所有产品（注意是店铺的产品，不是用户的产品）
        products = Product.objects.filter(shop=shop)
        serializer = ProductSerializer(products, many=True)
        return Response(serializer.data)

    elif request.method == 'POST':
        # 创建产品时关联到店铺
        data = request.data.copy()

        # 检查该店铺下产品编号是否已存在
        if Product.objects.filter(shop=shop, code=data.get('code')).exists():
            return Response({"error": "产品编号已存在"}, status=status.HTTP_400_BAD_REQUEST)

        # 添加店铺信息
        data['shop'] = shop.id

        serializer = ProductSerializer(data=data)
        if serializer.is_valid():
            # 保存产品
            product = serializer.save()

            # 自动记录新建商品操作
            InventoryOperation.objects.create(
                product=product,
                operation_type='NEW',
                quantity=product.stock,
                note="新建商品",
                operator=username  # 记录操作人
            )
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


# 库存操作视图
@api_view(['GET', 'POST'])
def inventory_operation(request):
    # 从请求中获取用户信息
    username = request.GET.get('username') or request.data.get('username')

    if not username:
        return Response({"error": "必须提供用户名"}, status=status.HTTP_400_BAD_REQUEST)

    try:
        # 查找用户并获取关联的店铺
        user = UserData.objects.get(username=username)
        shop = user.shop
    except UserData.DoesNotExist:
        return Response({"error": "用户不存在"}, status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        # 获取该店铺的所有操作记录
        operations = InventoryOperation.objects.filter(product__shop=shop)
        serializer = OperationSerializer(operations, many=True)
        return Response(serializer.data)

    elif request.method == 'POST':
        print("原始请求数据:", request.data)
        serializer = OperationSerializer(data=request.data)
        if serializer.is_valid():
            try:
                # 从序列化器中获取验证后的数据
                validated_data = serializer.validated_data

                # 获取产品代码并查找对应产品 (仅限于该店铺的产品)
                product_code = validated_data.get('write_product_code')
                product = Product.objects.get(code=product_code, shop=shop)

                # 更新产品库存
                if validated_data['operation_type'] == 'IN':
                    product.stock += validated_data['quantity']
                elif validated_data['operation_type'] == 'OUT':
                    if product.stock < validated_data['quantity']:
                        return Response(
                            {"error": "库存不足"},
                            status=status.HTTP_400_BAD_REQUEST
                        )
                    product.stock -= validated_data['quantity']

                product.save()

                # 手动创建操作记录实例
                operation = InventoryOperation.objects.create(
                    product=product,
                    operation_type=validated_data['operation_type'],
                    quantity=validated_data['quantity'],
                    note=validated_data.get('note', ''),
                    operator=username  # 使用传入的用户名作为操作人
                )

                # 返回创建的实例数据
                return Response(OperationSerializer(operation).data)

            except Product.DoesNotExist:
                return Response(
                    {"error": f"未找到商品编号为 {product_code} 的商品"},
                    status=status.HTTP_404_NOT_FOUND
                )
            except Exception as e:
                return Response(
                    {"error": f"操作失败: {str(e)}"},
                    status=status.HTTP_500_INTERNAL_SERVER_ERROR
                )
        else:
            print("序列化器错误:", serializer.errors)
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


# 删除商品视图
@api_view(['DELETE'])
def delete_product(request, product_code):
    """删除商品"""
    # 从请求中获取用户信息
    username = request.GET.get('username')

    if not username:
        return Response({"error": "必须提供用户名"}, status=status.HTTP_400_BAD_REQUEST)

    try:
        # 查找用户并获取关联的店铺
        user = UserData.objects.get(username=username)
        shop = user.shop
    except UserData.DoesNotExist:
        return Response({"error": "用户不存在"}, status=status.HTTP_404_NOT_FOUND)

    try:
        # 查找该店铺的指定商品
        product = Product.objects.get(code=product_code, shop=shop)

        # 先保存产品信息，用于创建删除记录
        product_name = product.name
        current_stock = product.stock

        # 创建删除操作记录
        InventoryOperation.objects.create(
            product=product,  # 删除前关联到产品
            product_code=product_code,  # 保存编号
            product_name=product_name,  # 保存名称
            operation_type='DEL',
            quantity=current_stock,
            note="删除商品",
            operator=username  # 记录删除操作人
        )

        # 删除商品
        product.delete()

        return Response({"message": "商品删除成功"}, status=status.HTTP_200_OK)
    except Product.DoesNotExist:
        return Response({"error": "商品不存在"}, status=status.HTTP_404_NOT_FOUND)
    except Exception as e:
        return Response({"error": f"删除商品时出错: {str(e)}"},
                       status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['POST'])
def verify_invite_code(request):
    """验证邀请码"""
    store_name = request.data.get('store_name')
    invite_code = request.data.get('invite_code')

    if not store_name:
        return Response({
            'status': 'error',
            'message': '店铺名不能为空'
        }, status=status.HTTP_400_BAD_REQUEST)

    # 检查是否是第一次注册该店铺名
    existing_shop = Shop.objects.filter(name=store_name).first()

    # 如果是首次注册该店铺名，不需要邀请码
    if not existing_shop:
        return Response({
            'status': 'success',
            'message': '首次注册该店铺，无需邀请码',
            'is_first_store': True
        })

    # 否则，需要验证邀请码
    if not invite_code:
        return Response({
            'status': 'error',
            'message': '该店铺已存在，需要邀请码'
        }, status=status.HTTP_400_BAD_REQUEST)

    # 验证邀请码是否正确
    if existing_shop.invite_code and check_password(invite_code, existing_shop.invite_code):

    #if existing_shop.invite_code == invite_code:
        return Response({
            'status': 'success',
            'message': '邀请码验证成功',
            'is_first_store': False
        })
    else:
        return Response({
            'status': 'error',
            'message': '邀请码无效，请联系店铺管理员获取正确邀请码'
        }, status=status.HTTP_400_BAD_REQUEST)


# 保存邀请码视图
@api_view(['POST'])
def save_invite_code(request):
    """保存店铺邀请码"""
    store_name = request.data.get('store_name')
    invite_code = request.data.get('invite_code')

    if not store_name or not invite_code:
        return Response({
            'status': 'error',
            'message': '店铺名和邀请码不能为空'
        }, status=status.HTTP_400_BAD_REQUEST)

    try:
        # 查找该店铺
        shop = Shop.objects.filter(name=store_name).first()

        if not shop:
            return Response({
                'status': 'error',
                'message': '未找到该店铺'
            }, status=status.HTTP_404_NOT_FOUND)

        # 保存邀请码
        shop.invite_code = invite_code
        shop.save()

        return Response({
            'status': 'success',
            'message': '邀请码保存成功'
        })
    except Exception as e:
        return Response({
            'status': 'error',
            'message': f'保存邀请码失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


# 普通商单视图
@api_view(['GET', 'POST'])
def normal_orders(request):
    """获取或创建普通商单"""
    username = request.GET.get('username') or request.data.get('username')

    if not username:
        return Response({"error": "必须提供用户名"}, status=status.HTTP_400_BAD_REQUEST)

    try:
        user = UserData.objects.get(username=username)
        shop = user.shop
    except UserData.DoesNotExist:
        return Response({"error": "用户不存在"}, status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        # 获取该店铺的所有普通商单
        orders = NormalOrder.objects.filter()
        serializer = NormalOrderSerializer(orders, many=True)
        return Response(serializer.data)

    elif request.method == 'POST':
        data = request.data.copy()
        data['username'] = username  # 添加用户名字段用于找到创建者和店铺
        serializer = NormalOrderSerializer(data=data)

        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)



import logging
from django.http import JsonResponse
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from .models import UserData, Shop, PrivateOrder
from .serializers import PrivateOrderSerializer
import json
from qkd_app.utils import AESCipher

# 获取 logger 实例
logger = logging.getLogger(__name__)
# 的隐私商单视图
@api_view(['GET', 'POST'])
def private_orders(request):
    #获取或创建隐私商单（带QKD加密）
    username = request.GET.get('username') or request.data.get('username')
    qkd_key = request.GET.get('qkd_key') or request.data.get('qkd_key')

    if not username:
        return Response({"error": "必须提供用户名"}, status=status.HTTP_400_BAD_REQUEST)

    if not qkd_key:
        return Response({"error": "必须提供QKD密钥"}, status=status.HTTP_400_BAD_REQUEST)

    try:
        user = UserData.objects.get(username=username)
        shop = user.shop
    except UserData.DoesNotExist:
        return Response({"error": "用户不存在"}, status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        # 获取该店铺的所有隐私商单
        orders = PrivateOrder.objects.filter()
        serializer = PrivateOrderSerializer(orders, many=True)

        # 创建加密响应
        try:
            # 将数据转换为JSON字符串
            order_data = json.dumps(serializer.data)

            # 先确保导入了必要的模块


            # 使用提供的QKD密钥临时存储到qkd_keys中
            from qkd_app.models import qkd_keys
            # 临时存储密钥，确保可以通过用户名找到它
            original_key = qkd_keys.get(username, None)
            qkd_keys[username] = qkd_key  # 临时设置用户的密钥

            # 使用AESCipher加密数据（传递用户名）
            encrypted_data = AESCipher.encrypt(order_data, username)

            # 恢复原始密钥状态
            if original_key:
                qkd_keys[username] = original_key  # 恢复原始密钥
            else:
                qkd_keys.pop(username, None)  # 移除临时添加的密钥

            if encrypted_data is None:
                return Response({"error": "数据加密失败"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

            orders = PrivateOrder.objects.filter(shop=shop)
            print(f"查询到 {orders.count()} 条隐私商单")
            for order in orders:
                print(f"订单: {order.order_id}, 客户: {order.customer}, 商品: {order.product}")

            # 返回加密数据
            return Response({
                "status": "success",
                "encrypted": True,
                "data": encrypted_data
            })
        except Exception as e:
            import logging
            logger = logging.getLogger(__name__)
            logger.error(f"加密隐私商单数据时出错: {str(e)}")
            return Response({"error": f"加密数据失败: {str(e)}"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    elif request.method == 'POST':
        # POST方法保持不变
        data = request.data.copy()
        data['username'] = username  # 添加用户名用于找到创建者和店铺

        # 确保提供了QKD密钥
        if 'qkd_key' not in data or not data['qkd_key']:
            return Response({"error": "必须提供QKD密钥"}, status=status.HTTP_400_BAD_REQUEST)

        serializer = PrivateOrderSerializer(data=data)

        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)



# 在views.py中添加
@api_view(['GET'])
def user_info(request):
    #获取用户详细信息，包括所属店铺
    username = request.GET.get('username')

    if not username:
        return Response({"error": "必须提供用户名"}, status=status.HTTP_400_BAD_REQUEST)

    try:
        user = UserData.objects.get(username=username)
        return Response({
            "user_id": user.id,
            "username": user.username,
            "email": user.email,
            "phone": user.phone,
            "shop_id": user.shop.id,
            "shop_name": user.shop.name,
            "shop_type": user.shop.shop_type,
            "is_cross_border": user.shop.is_cross_border
        })
    except UserData.DoesNotExist:
        return Response({"error": "用户不存在"}, status=status.HTTP_404_NOT_FOUND)



from django.shortcuts import render, redirect
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from django.shortcuts import render
from django.utils import timezone
from .models import UserData, Product, InventoryOperation
from django.shortcuts import render, redirect
from django.http import JsonResponse, HttpResponse
from django.db import models  # 添加这行导入语句
from .models import UserData, Shop, Product, InventoryOperation, NormalOrder, PrivateOrder

def login_view(request):
    # 处理 POST 请求时进行登录验证
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')

        # 硬编码的用户名和密码
        if username == 'admin' and password == '123':
            # 如果用户名和密码匹配，跳转到 index 页面
            return redirect('index')  # 这里是跳转到 index 页面
        else:
            # 如果用户名或密码错误，返回错误信息
            return render(request, 'login.html', {'error_message': '用户名或密码错误'})

    # 如果是 GET 请求，直接渲染登录页面
    return render(request, 'login.html')


def index_view(request):
    # 获取所有产品数据
    products = Product.objects.all()

    # 获取所有入库数据
    inbound_operations = InventoryOperation.objects.filter(operation_type='IN').order_by('-timestamp')

    # 获取所有出库数据
    outbound_operations = InventoryOperation.objects.filter(operation_type='OUT').order_by('-timestamp')

    # 打印调试信息
    print(f"查询到的产品数量: {products.count()}")
    for p in products:
        print(f"产品: ID={p.id}, 名称={p.name}, 编码={p.code}, 规格={p.spec}, 库存={p.stock}")

    # 初始化数据结构来存储图表数据
    operation_data = {}

    # 处理入库数据
    for op in inbound_operations:
        time_key = op.timestamp.strftime('%Y-%m-%d %H:%M')
        if time_key not in operation_data:
            operation_data[time_key] = {'in': 0, 'out': 0}
        operation_data[time_key]['in'] += op.quantity

    # 处理出库数据
    for op in outbound_operations:
        time_key = op.timestamp.strftime('%Y-%m-%d %H:%M')
        if time_key not in operation_data:
            operation_data[time_key] = {'in': 0, 'out': 0}
        operation_data[time_key]['out'] += op.quantity

    # 排序时间并准备图表数据
    sorted_times = sorted(operation_data.keys())

    # 准备图表数据
    times = sorted_times
    inbound_by_time = [operation_data[time]['in'] for time in sorted_times]
    outbound_by_time = [operation_data[time]['out'] for time in sorted_times]

    context = {
        'products': products,
        'times': times,
        'inbound_by_time': inbound_by_time,
        'outbound_by_time': outbound_by_time,
    }

    return render(request, 'index.html', context)


from django.shortcuts import render
from django.db.models import Count
from .models import UserData, Product, InventoryOperation


def user_view(request):
    # 查询商铺类型分布 - 使用 my1_shop 表数据
    shop_types = {
        'normal': Shop.objects.filter(shop_type='normal').count(),
        'flagship': Shop.objects.filter(shop_type='flagship').count(),
        'franchise': Shop.objects.filter(shop_type='franchise').count(),
        'exclusive': Shop.objects.filter(shop_type='exclusive').count()
    }

    # 查询用户地区分布 - 使用 my1_userdata 表数据
    provinces = UserData.objects.values('province').annotate(count=Count('id'))
    province_data = {}
    for province in provinces:
        # 处理 NULL 值
        if province['province'] is None:
            province_key = '未知地区'
        else:
            province_key = province['province']
        province_data[province_key] = province['count']

    # 查询跨境与非跨境用户 - 使用 my1_shop 表数据
    cross_border_shops = Shop.objects.filter(is_cross_border=True).count()
    non_cross_border_shops = Shop.objects.filter(is_cross_border=False).count()

    # 按月份统计跨境和非跨境商铺
    # 12个月的跨境商铺数据
    cross_border_monthly = [1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3]
    # 12个月的非跨境商铺数据
    non_cross_border_monthly = [1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 4, 4]

    context = {
        'shop_types': shop_types,
        'province_data': province_data,
        'cross_border_shops': cross_border_shops,
        'non_cross_border_shops': non_cross_border_shops,
        'cross_border_monthly': cross_border_monthly,
        'non_cross_border_monthly': non_cross_border_monthly
    }

    return render(request, 'user.html', context)


from django.shortcuts import render
from django.db.models import Sum
from .models import Shop, Product, InventoryOperation


def shop_view(request):
    # 查询所有店铺
    shops = Shop.objects.all()

    # 商家数据列表
    shop_data = []

    for shop in shops:
        # 计算每个店铺的相关指标

        # 获取该店铺的所有产品
        shop_products = Product.objects.filter(shop=shop)

        # 计算该店铺的入库数量总和（只考虑IN和NEW操作）
        in_stock = InventoryOperation.objects.filter(
            product__in=shop_products,
            operation_type__in=['IN', 'NEW']
        ).aggregate(total=Sum('quantity'))['total'] or 0

        # 计算该店铺的出库数量总和（只考虑OUT操作）
        out_stock = InventoryOperation.objects.filter(
            product__in=shop_products,
            operation_type='OUT'
        ).aggregate(total=Sum('quantity'))['total'] or 0

        # 计算商品盈利值（售价-进价）× 库存
        shop_profit = 0
        for product in shop_products:
            # 将Decimal转换为float
            profit_per_item = float(product.price) - float(product.cost)
            shop_profit += profit_per_item * product.stock

        # 计算热度指数：热度 = (入库数量 × 0.3 + 出库数量 × 0.5 + 商品盈利值 × 0.002)
        hot_index = (in_stock * 0.3 + out_stock * 0.5 + shop_profit * 0.002)

        # 添加到商家数据列表
        shop_data.append({
            'id': shop.id,
            'name': shop.name,
            'shop_type': shop.get_shop_type_display(),
            'in_stock': in_stock,
            'out_stock': out_stock,
            'profit': shop_profit,
            'hot_index': round(hot_index, 2)
        })

    # 按热度指数排序
    shop_data.sort(key=lambda x: x['hot_index'], reverse=True)

    # 提取前5名店铺的名称和热度指数用于图表
    top_shops = shop_data[:5]
    shop_names = [shop['name'] for shop in top_shops]
    hot_indices = [shop['hot_index'] for shop in top_shops]

    context = {
        'shop_data': shop_data,
        'shop_names': shop_names,
        'hot_indices': hot_indices
    }

    return render(request, 'shop.html', context)


from django.shortcuts import render
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
import httpx


API_KEY = 'sk-302b312594814d0d80f45177777922c0'
API_URL = "https://api.deepseek.com/v1/chat/completions"


@csrf_exempt
def chat_view(request):
    if request.method == "POST":
        user_input = request.POST.get("message", "")

        # 使用同步客户端
        with httpx.Client() as client:
            try:
                response = client.post(
                    API_URL,
                    headers={
                        "Authorization": f"Bearer {API_KEY}",
                        "Content-Type": "application/json"
                    },
                    json={
                        "model": "deepseek-chat",
                        "messages": [
                            {"role": "system", "content": "你是一个专业的客服助手，请用正式的语气回答用户的问题。"},
                            {"role": "user", "content": user_input}
                        ],
                        "stream": False  # 关闭流式响应
                    },
                    timeout=30
                )

                data = response.json()
                bot_reply = data["choices"][0]["message"]["content"]
                return JsonResponse({'reply': bot_reply})

            except Exception as e:
                return JsonResponse({'error': str(e)}, status=500)

    return render(request, 'index.html')


@api_view(['POST'])
def create_operation_record(request):
    #手动创建操作历史记录
    try:
        data = request.data
        # 验证必要字段
        required_fields = ['product_code', 'product_name', 'operation_type', 'quantity', 'operator']
        for field in required_fields:
            if field not in data:
                return Response({"error": f"缺少必要字段: {field}"}, status=status.HTTP_400_BAD_REQUEST)

        # 创建记录
        InventoryOperation.objects.create(
            product=None,  # 不关联到产品对象
            product_code=data['product_code'],
            product_name=data['product_name'],
            operation_type=data['operation_type'],
            quantity=data['quantity'],
            note=data.get('note', ''),
            operator=data['operator']
        )

        return Response({"message": "操作记录创建成功"}, status=status.HTTP_201_CREATED)
    except Exception as e:
        return Response({"error": f"创建操作记录失败: {str(e)}"},
                        status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['POST'])
def check_is_first_user(request):
    #检查用户是否是店铺的第一个注册用户
    username = request.data.get("username")

    if not username:
        return Response({"status": "error", "message": "用户名不能为空"}, status=status.HTTP_400_BAD_REQUEST)

    try:
        # 获取用户及其所属的店铺
        user = UserData.objects.get(username=username)
        shop = user.shop

        # 获取该店铺的所有用户，按创建时间排序
        shop_users = UserData.objects.filter(shop=shop).order_by('created_at')

        # 如果当前用户是该店铺的第一个用户，返回True
        is_first_user = shop_users.first().username == username

        return Response({
            "status": "success",
            "is_first_user": is_first_user,
            "message": "用户是该店铺的第一个注册用户" if is_first_user else "用户不是该店铺的第一个注册用户"
        })
    except UserData.DoesNotExist:
        return Response({"status": "error", "message": "用户不存在"}, status=status.HTTP_404_NOT_FOUND)
    except Exception as e:
        return Response({"status": "error", "message": f"检查失败: {str(e)}"},
                        status=status.HTTP_500_INTERNAL_SERVER_ERROR)

